package entity

import (
	"gorm.io/gorm"
)

type Address struct {
	gorm.Model
	Region     string `gorm:"type:varchar(255);not null;comment:地区"`
	Detail     string `gorm:"type:varchar(255);not null;comment:地址"`
	Phone      string `gorm:"type:varchar(11);not null;comment:电话"`
	Name       string `gorm:"type:varchar(255);not null;comment:姓名"`
	Default    bool   `gorm:"type:tinyint(1);not null;default:0;comment:是否默认"`
	UserId     int64  `gorm:"type:int;not null;comment:用户id"`
	PostalCode string `gorm:"type:varchar(6);comment:邮编"`
}

func (Address) TableName() string {
	return "l_address"
}

func (a *Address) Save(db *gorm.DB) error {
	return db.Create(a).Error
}

func (a *Address) Delete(db *gorm.DB) error {
	return db.Where("id = ?", a.ID).Delete(a).Error
}

func (a *Address) FindById(db *gorm.DB, userId int64, id uint) error {
	err := db.Where("id = ? And user_id = ?", id, userId).First(a).Error
	if err != nil {
		return err
	}
	return nil
}

func (a *Address) ClearPreDefault(db *gorm.DB, userId int64) error {
	err := db.Where("user_id = ? And `default` = ?", userId, 1).First(a).Error

	if err == nil {
		err = db.Model(&a).Update("default", 0).Error
		if err != nil {
			return err
		}
	}

	return nil
}

func (a *Address) SetDefault(db *gorm.DB) error {
	return db.Model(a).Update("default", 1).Error
}
